Тест. Практика построения регрессии


In [1]:
from __future__ import division

import numpy as np
import pandas as pd

from scipy import stats
import statsmodels.formula.api as smf
import statsmodels.stats.api as sms

%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"


C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\statsmodels\compat\pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
  from pandas.core import datetools

Давайте проанализируем данные опроса 4361 женщин из Ботсваны:

botswana.tsv

О каждой из них мы знаем:

сколько детей она родила (признак ceb)

возраст (age)

длительность получения образования (educ)

религиозная принадлежность (religion)

идеальное, по её мнению, количество детей в семье (idlnchld)

была ли она когда-нибудь замужем (evermarr)

возраст первого замужества (agefm)

длительность получения образования мужем (heduc)

знает ли она о методах контрацепции (knowmeth)

использует ли она методы контрацепции (usemeth)

живёт ли она в городе (urban)

есть ли у неё электричество, радио, телевизор и велосипед (electric, radio, tv, bicycle)

Давайте научимся оценивать количество детей ceb по остальным признакам.

Загрузите данные и внимательно изучите их. Сколько разных значений принимает признак religion?


In [2]:
botswana = pd.read_csv('botswana.tsv', delimiter='\t')
botswana.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4361 entries, 0 to 4360
Data columns (total 15 columns):
ceb         4361 non-null int64
age         4361 non-null int64
educ        4361 non-null int64
religion    4361 non-null object
idlnchld    4241 non-null float64
knowmeth    4354 non-null float64
usemeth     4290 non-null float64
evermarr    4361 non-null int64
agefm       2079 non-null float64
heduc       1956 non-null float64
urban       4361 non-null int64
electric    4358 non-null float64
radio       4359 non-null float64
tv          4359 non-null float64
bicycle     4358 non-null float64
dtypes: float64(9), int64(5), object(1)
memory usage: 511.1+ KB

In [3]:
botswana.columns
botswana.head()


Out[3]:
Index([u'ceb', u'age', u'educ', u'religion', u'idlnchld', u'knowmeth',
       u'usemeth', u'evermarr', u'agefm', u'heduc', u'urban', u'electric',
       u'radio', u'tv', u'bicycle'],
      dtype='object')
Out[3]:
ceb age educ religion idlnchld knowmeth usemeth evermarr agefm heduc urban electric radio tv bicycle
0 0 18 10 catholic 4.0 1.0 1.0 0 NaN NaN 1 1.0 1.0 1.0 1.0
1 2 43 11 protestant 2.0 1.0 1.0 1 20.0 14.0 1 1.0 1.0 1.0 1.0
2 0 49 4 spirit 4.0 1.0 0.0 1 22.0 1.0 1 1.0 1.0 0.0 0.0
3 0 24 12 other 2.0 1.0 0.0 0 NaN NaN 1 1.0 1.0 1.0 1.0
4 3 32 13 other 3.0 1.0 1.0 1 24.0 12.0 1 1.0 1.0 1.0 1.0

In [4]:
print(botswana.religion.value_counts())


spirit        1841
other         1080
protestant     993
catholic       447
Name: religion, dtype: int64

Во многих признаках есть пропущенные значения. Сколько объектов из 4361 останется, если выбросить все, содержащие пропуски?


In [5]:
bw_wo_nan = botswana.dropna()
bw_wo_nan.shape


Out[5]:
(1834, 15)

В разных признаках пропуски возникают по разным причинам и должны обрабатываться по-разному.

Например, в признаке agefm пропуски стоят только там, где evermarr=0, то есть, они соответствуют женщинам, никогда не выходившим замуж. Таким образом, для этого признака NaN соответствует значению "не применимо".

В подобных случаях, когда признак x1 на части объектов в принципе не может принимать никакие значения, рекомендуется поступать так:

создать новый бинарный признак x2={1,0,x1='не применимо',иначе; заменить "не применимо" в x1 на произвольную константу c, которая среди других значений x1 не встречается. Теперь, когда мы построим регрессию на оба признака и получим модель вида y=β0+β1x1+β2x2, на тех объектах, где x1 было измерено, регрессионное уравнение примет вид y=β0+β1x, а там, где x1 было "не применимо", получится y=β0+β1c+β2. Выбор c влияет только на значение и интерпретацию β2, но не β1.

Давайте используем этот метод для обработки пропусков в agefm и heduc.

Создайте признак nevermarr, равный единице там, где в agefm пропуски. Удалите признак evermarr — в сумме с nevermarr он даёт константу, значит, в нашей матрице X будет мультиколлинеарность. Замените NaN в признаке agefm на cagefm=0. У объектов, где nevermarr = 1, замените NaN в признаке heduc на cheduc1=−1 (ноль использовать нельзя, так как он уже встречается у некоторых объектов выборки). Сколько осталось пропущенных значений в признаке heduc?


In [6]:
botswana['nevermarr'] = [1 if botswana.loc[i, 'evermarr'] == 0 else 0 for i in range(botswana.shape[0])]
botswana.head()


Out[6]:
ceb age educ religion idlnchld knowmeth usemeth evermarr agefm heduc urban electric radio tv bicycle nevermarr
0 0 18 10 catholic 4.0 1.0 1.0 0 NaN NaN 1 1.0 1.0 1.0 1.0 1
1 2 43 11 protestant 2.0 1.0 1.0 1 20.0 14.0 1 1.0 1.0 1.0 1.0 0
2 0 49 4 spirit 4.0 1.0 0.0 1 22.0 1.0 1 1.0 1.0 0.0 0.0 0
3 0 24 12 other 2.0 1.0 0.0 0 NaN NaN 1 1.0 1.0 1.0 1.0 1
4 3 32 13 other 3.0 1.0 1.0 1 24.0 12.0 1 1.0 1.0 1.0 1.0 0

In [7]:
np.unique(botswana.agefm[botswana.agefm.notnull()].values)


Out[7]:
array([ 10.,  11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,
        21.,  22.,  23.,  24.,  25.,  26.,  27.,  28.,  29.,  30.,  31.,
        32.,  33.,  34.,  35.,  36.,  37.,  38.,  39.,  40.,  41.,  43.,
        44.,  46.])

In [8]:
botswana.agefm[botswana.agefm.isnull()] = 0
botswana.head()


C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
Out[8]:
ceb age educ religion idlnchld knowmeth usemeth evermarr agefm heduc urban electric radio tv bicycle nevermarr
0 0 18 10 catholic 4.0 1.0 1.0 0 0.0 NaN 1 1.0 1.0 1.0 1.0 1
1 2 43 11 protestant 2.0 1.0 1.0 1 20.0 14.0 1 1.0 1.0 1.0 1.0 0
2 0 49 4 spirit 4.0 1.0 0.0 1 22.0 1.0 1 1.0 1.0 0.0 0.0 0
3 0 24 12 other 2.0 1.0 0.0 0 0.0 NaN 1 1.0 1.0 1.0 1.0 1
4 3 32 13 other 3.0 1.0 1.0 1 24.0 12.0 1 1.0 1.0 1.0 1.0 0

In [9]:
del botswana['evermarr']

In [10]:
botswana.heduc[botswana.heduc.isnull() & botswana.nevermarr.values == 1] = -1
botswana.head()


C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
Out[10]:
ceb age educ religion idlnchld knowmeth usemeth agefm heduc urban electric radio tv bicycle nevermarr
0 0 18 10 catholic 4.0 1.0 1.0 0.0 -1.0 1 1.0 1.0 1.0 1.0 1
1 2 43 11 protestant 2.0 1.0 1.0 20.0 14.0 1 1.0 1.0 1.0 1.0 0
2 0 49 4 spirit 4.0 1.0 0.0 22.0 1.0 1 1.0 1.0 0.0 0.0 0
3 0 24 12 other 2.0 1.0 0.0 0.0 -1.0 1 1.0 1.0 1.0 1.0 1
4 3 32 13 other 3.0 1.0 1.0 24.0 12.0 1 1.0 1.0 1.0 1.0 0

In [11]:
botswana.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4361 entries, 0 to 4360
Data columns (total 15 columns):
ceb          4361 non-null int64
age          4361 non-null int64
educ         4361 non-null int64
religion     4361 non-null object
idlnchld     4241 non-null float64
knowmeth     4354 non-null float64
usemeth      4290 non-null float64
agefm        4361 non-null float64
heduc        4238 non-null float64
urban        4361 non-null int64
electric     4358 non-null float64
radio        4359 non-null float64
tv           4359 non-null float64
bicycle      4358 non-null float64
nevermarr    4361 non-null int64
dtypes: float64(9), int64(5), object(1)
memory usage: 511.1+ KB

In [12]:
botswana.heduc.isnull().value_counts()


Out[12]:
False    4238
True      123
Name: heduc, dtype: int64

Избавимся от оставшихся пропусков.

Для признаков idlnchld, heduc и usemeth проведите операцию, аналогичную предыдущей: создайте индикаторы пропусков по этим признакам (idlnchld_noans, heduc_noans, usemeth_noans), замените пропуски на нехарактерные значения (cidlnchld=−1, cheduc2=−2 (значение -1 мы уже использовали), cusemeth=−1).

Остались только пропуски в признаках knowmeth, electric, radio, tv и bicycle. Их очень мало, так что удалите объекты, на которых их значения пропущены.

Какого размера теперь наша матрица данных? Умножьте количество строк на количество всех столбцов (включая отклик ceb).


In [13]:
botswana['idlnchld_noans'] = 0
botswana.loc[botswana.idlnchld.isnull(), 'idlnchld_noans'] = 1

botswana['heduc_noans'] = 0
botswana.loc[botswana.heduc.isnull(), 'heduc_noans'] = 1

botswana['usemeth_noans'] = 0
botswana.loc[botswana.usemeth.isnull(), 'usemeth_noans'] = 1

botswana.head()


Out[13]:
ceb age educ religion idlnchld knowmeth usemeth agefm heduc urban electric radio tv bicycle nevermarr idlnchld_noans heduc_noans usemeth_noans
0 0 18 10 catholic 4.0 1.0 1.0 0.0 -1.0 1 1.0 1.0 1.0 1.0 1 0 0 0
1 2 43 11 protestant 2.0 1.0 1.0 20.0 14.0 1 1.0 1.0 1.0 1.0 0 0 0 0
2 0 49 4 spirit 4.0 1.0 0.0 22.0 1.0 1 1.0 1.0 0.0 0.0 0 0 0 0
3 0 24 12 other 2.0 1.0 0.0 0.0 -1.0 1 1.0 1.0 1.0 1.0 1 0 0 0
4 3 32 13 other 3.0 1.0 1.0 24.0 12.0 1 1.0 1.0 1.0 1.0 0 0 0 0

In [16]:
botswana.idlnchld[botswana.idlnchld.isnull()] = -1
botswana.heduc[botswana.heduc.isnull()] = -2
botswana.usemeth[botswana.usemeth.isnull()] = -1


C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\ipykernel_launcher.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  
C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\ipykernel_launcher.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  This is separate from the ipykernel package so we can avoid doing imports until

In [17]:
botswana.info()


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4361 entries, 0 to 4360
Data columns (total 18 columns):
ceb               4361 non-null int64
age               4361 non-null int64
educ              4361 non-null int64
religion          4361 non-null object
idlnchld          4361 non-null float64
knowmeth          4354 non-null float64
usemeth           4361 non-null float64
agefm             4361 non-null float64
heduc             4361 non-null float64
urban             4361 non-null int64
electric          4358 non-null float64
radio             4359 non-null float64
tv                4359 non-null float64
bicycle           4358 non-null float64
nevermarr         4361 non-null int64
idlnchld_noans    4361 non-null int64
heduc_noans       4361 non-null int64
usemeth_noans     4361 non-null int64
dtypes: float64(9), int64(8), object(1)
memory usage: 613.3+ KB

In [18]:
botswana = botswana.dropna()

In [19]:
botswana.info()


<class 'pandas.core.frame.DataFrame'>
Int64Index: 4348 entries, 0 to 4360
Data columns (total 18 columns):
ceb               4348 non-null int64
age               4348 non-null int64
educ              4348 non-null int64
religion          4348 non-null object
idlnchld          4348 non-null float64
knowmeth          4348 non-null float64
usemeth           4348 non-null float64
agefm             4348 non-null float64
heduc             4348 non-null float64
urban             4348 non-null int64
electric          4348 non-null float64
radio             4348 non-null float64
tv                4348 non-null float64
bicycle           4348 non-null float64
nevermarr         4348 non-null int64
idlnchld_noans    4348 non-null int64
heduc_noans       4348 non-null int64
usemeth_noans     4348 non-null int64
dtypes: float64(9), int64(8), object(1)
memory usage: 645.4+ KB

In [20]:
elem_num = botswana.shape[0] * botswana.shape[1]
print('Array size: %d' % elem_num)


Array size: 78264

Постройте регрессию количества детей ceb на все имеющиеся признаки методом smf.ols, как в разобранном до этого примере. Какой получился коэффициент детерминации R2? Округлите до трёх знаков после десятичной точки.

Если код из примера у вас не воспроизводится:

убедитесь, что вы сделали так:

import statsmodels.formula.api as smf возможно, вам нужно обновить библиотеку patsy; выполните в командной строке

pip install -U patsy


In [21]:
botswana.columns


Out[21]:
Index([u'ceb', u'age', u'educ', u'religion', u'idlnchld', u'knowmeth',
       u'usemeth', u'agefm', u'heduc', u'urban', u'electric', u'radio', u'tv',
       u'bicycle', u'nevermarr', u'idlnchld_noans', u'heduc_noans',
       u'usemeth_noans'],
      dtype='object')

In [22]:
formula = 'ceb ~ ' + ' + '.join(botswana.columns[1:])
formula


Out[22]:
'ceb ~ age + educ + religion + idlnchld + knowmeth + usemeth + agefm + heduc + urban + electric + radio + tv + bicycle + nevermarr + idlnchld_noans + heduc_noans + usemeth_noans'

In [23]:
reg_m = smf.ols(formula, data=botswana)
fitted_m = reg_m.fit()
print(fitted_m.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    ceb   R-squared:                       0.644
Model:                            OLS   Adj. R-squared:                  0.643
Method:                 Least Squares   F-statistic:                     412.5
Date:                Tue, 08 Aug 2017   Prob (F-statistic):               0.00
Time:                        20:13:48   Log-Likelihood:                -7732.1
No. Observations:                4348   AIC:                         1.550e+04
Df Residuals:                    4328   BIC:                         1.563e+04
Df Model:                          19                                         
Covariance Type:            nonrobust                                         
==========================================================================================
                             coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------------------
Intercept                 -1.0263      0.212     -4.835      0.000      -1.443      -0.610
religion[T.other]         -0.0830      0.083     -1.001      0.317      -0.245       0.080
religion[T.protestant]    -0.0149      0.082     -0.181      0.857      -0.176       0.146
religion[T.spirit]        -0.0191      0.077     -0.248      0.804      -0.171       0.132
age                        0.1703      0.003     51.891      0.000       0.164       0.177
educ                      -0.0724      0.007     -9.843      0.000      -0.087      -0.058
idlnchld                   0.0760      0.011      6.923      0.000       0.054       0.098
knowmeth                   0.5564      0.121      4.580      0.000       0.318       0.795
usemeth                    0.6473      0.048     13.424      0.000       0.553       0.742
agefm                     -0.0604      0.007     -9.213      0.000      -0.073      -0.048
heduc                     -0.0551      0.008     -6.838      0.000      -0.071      -0.039
urban                     -0.2137      0.047     -4.527      0.000      -0.306      -0.121
electric                  -0.2685      0.077     -3.479      0.001      -0.420      -0.117
radio                     -0.0235      0.051     -0.461      0.645      -0.123       0.076
tv                        -0.1451      0.093     -1.566      0.118      -0.327       0.037
bicycle                    0.2139      0.050      4.260      0.000       0.115       0.312
nevermarr                 -2.2393      0.148    -15.143      0.000      -2.529      -1.949
idlnchld_noans             0.6539      0.153      4.286      0.000       0.355       0.953
heduc_noans               -0.8724      0.145     -6.026      0.000      -1.156      -0.589
usemeth_noans              0.7652      0.196      3.910      0.000       0.382       1.149
==============================================================================
Omnibus:                      224.411   Durbin-Watson:                   1.887
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              859.014
Skew:                           0.003   Prob(JB):                    2.93e-187
Kurtosis:                       5.178   Cond. No.                         361.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

In [24]:
print(botswana.religion.value_counts())


spirit        1838
other         1076
protestant     989
catholic       445
Name: religion, dtype: int64

Проверьте критерием Бройша-Пагана гомоскедастичность ошибки в построенной модели. Выполняется ли она?

Если ошибка гетероскедастична, перенастройте модель, сделав поправку Уайта типа HC1.


In [25]:
print('Breusch-Pagan test: p=%f' % sms.het_breuschpagan(fitted_m.resid, fitted_m.model.exog)[1])


Breusch-Pagan test: p=0.000000

In [26]:
reg_m2 = smf.ols(formula, data=botswana)
fitted_m2 = reg_m2.fit(cov_type='HC1')
print(fitted_m2.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    ceb   R-squared:                       0.644
Model:                            OLS   Adj. R-squared:                  0.643
Method:                 Least Squares   F-statistic:                     345.0
Date:                Tue, 08 Aug 2017   Prob (F-statistic):               0.00
Time:                        20:14:47   Log-Likelihood:                -7732.1
No. Observations:                4348   AIC:                         1.550e+04
Df Residuals:                    4328   BIC:                         1.563e+04
Df Model:                          19                                         
Covariance Type:                  HC1                                         
==========================================================================================
                             coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------------------
Intercept                 -1.0263      0.266     -3.863      0.000      -1.547      -0.506
religion[T.other]         -0.0830      0.078     -1.067      0.286      -0.235       0.069
religion[T.protestant]    -0.0149      0.078     -0.192      0.848      -0.167       0.137
religion[T.spirit]        -0.0191      0.071     -0.268      0.789      -0.159       0.121
age                        0.1703      0.004     38.627      0.000       0.162       0.179
educ                      -0.0724      0.007     -9.924      0.000      -0.087      -0.058
idlnchld                   0.0760      0.015      5.236      0.000       0.048       0.104
knowmeth                   0.5564      0.174      3.190      0.001       0.215       0.898
usemeth                    0.6473      0.052     12.478      0.000       0.546       0.749
agefm                     -0.0604      0.010     -6.174      0.000      -0.080      -0.041
heduc                     -0.0551      0.009     -6.126      0.000      -0.073      -0.037
urban                     -0.2137      0.046     -4.667      0.000      -0.303      -0.124
electric                  -0.2685      0.072     -3.732      0.000      -0.410      -0.128
radio                     -0.0235      0.053     -0.446      0.656      -0.127       0.080
tv                        -0.1451      0.082     -1.766      0.077      -0.306       0.016
bicycle                    0.2139      0.048      4.412      0.000       0.119       0.309
nevermarr                 -2.2393      0.202    -11.082      0.000      -2.635      -1.843
idlnchld_noans             0.6539      0.216      3.029      0.002       0.231       1.077
heduc_noans               -0.8724      0.191     -4.556      0.000      -1.248      -0.497
usemeth_noans              0.7652      0.213      3.590      0.000       0.347       1.183
==============================================================================
Omnibus:                      224.411   Durbin-Watson:                   1.887
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              859.014
Skew:                           0.003   Prob(JB):                    2.93e-187
Kurtosis:                       5.178   Cond. No.                         361.
==============================================================================

Warnings:
[1] Standard Errors are heteroscedasticity robust (HC1)

Удалите из модели незначимые признаки religion, radio и tv. Проверьте гомоскедастичность ошибки, при необходимости сделайте поправку Уайта.

Не произошло ли значимого ухудшения модели после удаления этой группы признаков? Проверьте с помощью критерия Фишера. Чему равен его достигаемый уровень значимости? Округлите до четырёх цифр после десятичной точки.

Если достигаемый уровень значимости получился маленький, верните все удалённые признаки; если он достаточно велик, оставьте модель без религии, тв и радио.


In [32]:
formula2 = 'ceb ~ age + educ + idlnchld + knowmeth + usemeth + agefm + heduc + urban + electric + bicycle \
+ nevermarr + idlnchld_noans + heduc_noans + usemeth_noans'
formula2


Out[32]:
'ceb ~ age + educ + idlnchld + knowmeth + usemeth + agefm + heduc + urban + electric + bicycle + nevermarr + idlnchld_noans + heduc_noans + usemeth_noans'

In [33]:
reg_m3 = smf.ols(formula2, data=botswana)
fitted_m3 = reg_m3.fit()
print(fitted_m3.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    ceb   R-squared:                       0.644
Model:                            OLS   Adj. R-squared:                  0.643
Method:                 Least Squares   F-statistic:                     559.5
Date:                Tue, 08 Aug 2017   Prob (F-statistic):               0.00
Time:                        20:16:33   Log-Likelihood:                -7734.5
No. Observations:                4348   AIC:                         1.550e+04
Df Residuals:                    4333   BIC:                         1.559e+04
Df Model:                          14                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
Intercept         -1.0698      0.198     -5.393      0.000      -1.459      -0.681
age                0.1702      0.003     52.271      0.000       0.164       0.177
educ              -0.0729      0.007    -10.285      0.000      -0.087      -0.059
idlnchld           0.0770      0.011      7.042      0.000       0.056       0.098
knowmeth           0.5610      0.121      4.628      0.000       0.323       0.799
usemeth            0.6516      0.048     13.537      0.000       0.557       0.746
agefm             -0.0606      0.007     -9.240      0.000      -0.073      -0.048
heduc             -0.0573      0.008     -7.186      0.000      -0.073      -0.042
urban             -0.2190      0.047     -4.682      0.000      -0.311      -0.127
electric          -0.3207      0.070     -4.584      0.000      -0.458      -0.184
bicycle            0.2046      0.049      4.154      0.000       0.108       0.301
nevermarr         -2.2501      0.148    -15.231      0.000      -2.540      -1.961
idlnchld_noans     0.6565      0.152      4.310      0.000       0.358       0.955
heduc_noans       -0.8853      0.145     -6.122      0.000      -1.169      -0.602
usemeth_noans      0.7732      0.196      3.955      0.000       0.390       1.156
==============================================================================
Omnibus:                      224.096   Durbin-Watson:                   1.886
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              856.760
Skew:                           0.004   Prob(JB):                    9.06e-187
Kurtosis:                       5.175   Cond. No.                         345.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

In [34]:
print('Breusch-Pagan test: p=%f' % sms.het_breuschpagan(fitted_m3.resid, fitted_m3.model.exog)[1])


Breusch-Pagan test: p=0.000000

In [35]:
reg_m4 = smf.ols(formula2, data=botswana)
fitted_m4 = reg_m4.fit(cov_type='HC1')
print(fitted_m4.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    ceb   R-squared:                       0.644
Model:                            OLS   Adj. R-squared:                  0.643
Method:                 Least Squares   F-statistic:                     463.4
Date:                Tue, 08 Aug 2017   Prob (F-statistic):               0.00
Time:                        20:16:39   Log-Likelihood:                -7734.5
No. Observations:                4348   AIC:                         1.550e+04
Df Residuals:                    4333   BIC:                         1.559e+04
Df Model:                          14                                         
Covariance Type:                  HC1                                         
==================================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------
Intercept         -1.0698      0.258     -4.152      0.000      -1.575      -0.565
age                0.1702      0.004     38.746      0.000       0.162       0.179
educ              -0.0729      0.007    -10.311      0.000      -0.087      -0.059
idlnchld           0.0770      0.014      5.323      0.000       0.049       0.105
knowmeth           0.5610      0.174      3.224      0.001       0.220       0.902
usemeth            0.6516      0.052     12.571      0.000       0.550       0.753
agefm             -0.0606      0.010     -6.192      0.000      -0.080      -0.041
heduc             -0.0573      0.009     -6.440      0.000      -0.075      -0.040
urban             -0.2190      0.045     -4.814      0.000      -0.308      -0.130
electric          -0.3207      0.063     -5.076      0.000      -0.445      -0.197
bicycle            0.2046      0.048      4.279      0.000       0.111       0.298
nevermarr         -2.2501      0.202    -11.158      0.000      -2.645      -1.855
idlnchld_noans     0.6565      0.216      3.043      0.002       0.234       1.079
heduc_noans       -0.8853      0.191     -4.638      0.000      -1.259      -0.511
usemeth_noans      0.7732      0.212      3.639      0.000       0.357       1.190
==============================================================================
Omnibus:                      224.096   Durbin-Watson:                   1.886
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              856.760
Skew:                           0.004   Prob(JB):                    9.06e-187
Kurtosis:                       5.175   Cond. No.                         345.
==============================================================================

Warnings:
[1] Standard Errors are heteroscedasticity robust (HC1)

In [36]:
print('F=%f, p=%f, k1=%f' % reg_m2.fit().compare_f_test(reg_m4.fit()))


F=0.919236, p=0.467231, k1=5.000000

Признак usemeth_noans значим по критерию Стьюдента, то есть, при его удалении модель значимо ухудшится. Но вообще-то отдельно его удалять нельзя: из-за того, что мы перекодировали пропуски в usemeth произвольно выбранным значением cusemeth=−1, удалять usemeth_noans и usemeth можно только вместе.

Удалите из текущей модели usemeth_noans и usemeth. Проверьте критерием Фишера гипотезу о том, что качество модели не ухудшилось. Введите номер первой значащей цифры в достигаемом уровне значимости (например, если вы получили 5.5×10−8, нужно ввести 8).

Если достигаемый уровень значимости получился маленький, верните удалённые признаки; если он достаточно велик, оставьте модель без usemeth и usemeth_noans.


In [37]:
formula3 = 'ceb ~ age + educ + idlnchld + knowmeth + agefm + heduc + urban + electric + bicycle \
+ nevermarr + idlnchld_noans + heduc_noans'
formula3


Out[37]:
'ceb ~ age + educ + idlnchld + knowmeth + agefm + heduc + urban + electric + bicycle + nevermarr + idlnchld_noans + heduc_noans'

In [38]:
reg_m5 = smf.ols(formula3, data=botswana)
fitted_m5 = reg_m5.fit()
print(fitted_m5.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    ceb   R-squared:                       0.629
Model:                            OLS   Adj. R-squared:                  0.628
Method:                 Least Squares   F-statistic:                     611.3
Date:                Tue, 08 Aug 2017   Prob (F-statistic):               0.00
Time:                        20:19:20   Log-Likelihood:                -7825.7
No. Observations:                4348   AIC:                         1.568e+04
Df Residuals:                    4335   BIC:                         1.576e+04
Df Model:                          12                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
Intercept         -1.1931      0.202     -5.897      0.000      -1.590      -0.796
age                0.1776      0.003     54.368      0.000       0.171       0.184
educ              -0.0560      0.007     -7.862      0.000      -0.070      -0.042
idlnchld           0.0705      0.011      6.317      0.000       0.049       0.092
knowmeth           0.8739      0.121      7.203      0.000       0.636       1.112
agefm             -0.0649      0.007     -9.716      0.000      -0.078      -0.052
heduc             -0.0521      0.008     -6.411      0.000      -0.068      -0.036
urban             -0.1866      0.048     -3.917      0.000      -0.280      -0.093
electric          -0.3218      0.071     -4.505      0.000      -0.462      -0.182
bicycle            0.1979      0.050      3.935      0.000       0.099       0.296
nevermarr         -2.3625      0.150    -15.707      0.000      -2.657      -2.068
idlnchld_noans     0.5266      0.155      3.393      0.001       0.222       0.831
heduc_noans       -0.7947      0.147     -5.389      0.000      -1.084      -0.506
==============================================================================
Omnibus:                      250.641   Durbin-Watson:                   1.910
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              936.515
Skew:                          -0.158   Prob(JB):                    4.35e-204
Kurtosis:                       5.251   Cond. No.                         345.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

In [44]:
print('F=%f, p=%.40f, k1=%f' % reg_m4.fit().compare_f_test(reg_m5.fit()))


F=92.890582, p=0.0000000000000000000000000000000000000003, k1=2.000000

Посмотрите на доверительные интервалы для коэффициентов итоговой модели (не забудьте использовать поправку Уайта, если есть гетероскедастичность ошибки) и выберите правильные выводы.


In [45]:
print(fitted_m4.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    ceb   R-squared:                       0.644
Model:                            OLS   Adj. R-squared:                  0.643
Method:                 Least Squares   F-statistic:                     463.4
Date:                Tue, 08 Aug 2017   Prob (F-statistic):               0.00
Time:                        20:23:17   Log-Likelihood:                -7734.5
No. Observations:                4348   AIC:                         1.550e+04
Df Residuals:                    4333   BIC:                         1.559e+04
Df Model:                          14                                         
Covariance Type:                  HC1                                         
==================================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------
Intercept         -1.0698      0.258     -4.152      0.000      -1.575      -0.565
age                0.1702      0.004     38.746      0.000       0.162       0.179
educ              -0.0729      0.007    -10.311      0.000      -0.087      -0.059
idlnchld           0.0770      0.014      5.323      0.000       0.049       0.105
knowmeth           0.5610      0.174      3.224      0.001       0.220       0.902
usemeth            0.6516      0.052     12.571      0.000       0.550       0.753
agefm             -0.0606      0.010     -6.192      0.000      -0.080      -0.041
heduc             -0.0573      0.009     -6.440      0.000      -0.075      -0.040
urban             -0.2190      0.045     -4.814      0.000      -0.308      -0.130
electric          -0.3207      0.063     -5.076      0.000      -0.445      -0.197
bicycle            0.2046      0.048      4.279      0.000       0.111       0.298
nevermarr         -2.2501      0.202    -11.158      0.000      -2.645      -1.855
idlnchld_noans     0.6565      0.216      3.043      0.002       0.234       1.079
heduc_noans       -0.8853      0.191     -4.638      0.000      -1.259      -0.511
usemeth_noans      0.7732      0.212      3.639      0.000       0.357       1.190
==============================================================================
Omnibus:                      224.096   Durbin-Watson:                   1.886
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              856.760
Skew:                           0.004   Prob(JB):                    9.06e-187
Kurtosis:                       5.175   Cond. No.                         345.
==============================================================================

Warnings:
[1] Standard Errors are heteroscedasticity robust (HC1)

In [ ]: